﻿using System;
using System. Windows;
using System. Windows. Controls;
using Microsoft. Phone. Controls;
using NextApp. WP7. Models;
using NextApp. WP7. Util;
using System. Net;
using NextApp. WP7. AppConfig;
using System. Xml. Linq;
using System. Linq;
using System. Collections. Generic;
using Microsoft. Phone. Shell;
using System. Windows. Data;
using NextApp. WP7. Cache. NextApp;

namespace NextApp. WP7. View. Controls
{
    public partial class RelativePosts : UserControl
    {
        #region Initialize
        public RelativePosts( )
        {
            InitializeComponent( );
			this. Loaded += new RoutedEventHandler(RelativePosts_Loaded);
			//设置黑色字体提示
        }
        #endregion

        #region 分配相关文章数据
        public void SetDatas( RelativePost[ ] relativePosts )
        {
            if ( relativePosts. IsNotNullOrEmpty( ) )
            {
                this. list_RelativePosts. ItemsSource = relativePosts;
            }
            else
            {
                this. tblock_NoRelativePostsTip. Text = "没有相关文章";
                this. tblock_NoRelativePostsTip. Visibility = System. Windows. Visibility. Visible;
            }
        }
        #endregion

        #region 页面跳转 跳转到相关文章页面
        private void list_RelativePosts_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RelativePost p = this. list_RelativePosts. SelectedItem as RelativePost;
            if ( p != null )
            {
                this. list_RelativePosts. SelectedItem = null;
                //开始跳转
                ( Application. Current. RootVisual as PhoneApplicationFrame ). Navigate(new Uri(string. Format("/View/PostDetail.xaml?post={0}", p. id), UriKind. Relative));
            }
        }
        #endregion

        #region 将相关文章装订在桌面上
        private void menuItem_PostPinToStart_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            if ( menuItem != null )
            {
                RelativePost rp = menuItem. DataContext as RelativePost;
                if ( rp != null )
                {
                    Post p = new Post { id = rp. id, title = rp. title, author = rp. author };
                    Tool. CreateShellTile(p);
                }
            }
        }
        #endregion

		#region 删除文章
		private void menuItem_PostDelete_Click(object sender, RoutedEventArgs e)
		{
			if ( Config. Instance. IsLogin == false )
			{
				if ( MessageBox. Show("请先登录才能删除文章", "请登陆", MessageBoxButton. OKCancel) == MessageBoxResult. OK )
				{
					Util. Tool. Login( );
				}
			}
			else
			{
				RelativePost rp = (sender as MenuItem). DataContext as RelativePost;
				if ( rp != null )
				{
					this. DeletePost(rp. id);
				}
			}
		}
		private void DeletePost(int postID)
		{
			WebClient client = new WebClient( );
			client. Headers[ "User-Agent" ] = Config. Instance. Http_User_Agent;
			client. DownloadStringCompleted += (s, e1) =>
			{
				if ( e1. Error != null )
				{
					System. Diagnostics. Debug. WriteLine("删除文章失败: {0}", e1. Error. Message);
					return;
				}
				XElement osmobile;
				try
				{
					osmobile = XElement. Parse(e1. Result);
				}
				catch ( Exception )
				{
					return;
				}
				ApiError _error = new ApiError
				{
					errorCode = osmobile. Element("result"). Element("errorCode"). Value. ToInt32( ),
					errorMessage = osmobile. Element("result"). Element("errorMessage"). Value,
				};
				//隐藏进度条
				ProgressIndicatorIsVisible = false;
				//显示删除结果 如果删除成功 则清空该类型评论的缓存以及通知刷新评论
				if ( this.DisplayResult_DeletePost(_error) )
				{
					List<RelativePost> rps = (this. list_RelativePosts. ItemsSource as RelativePost[ ]).ToList();
					if ( rps != null )
					{
						rps. Remove(rps. FirstOrDefault(r => r. id == postID));
						this. list_RelativePosts. ItemsSource = rps. ToArray( );
					}
				}
			};
			client. Headers[ "Cookie" ] = Config. Instance. Cookie;
			if ( NextAppSingleton. Instance. url_comment_delete. IsNotNullOrWhitespace( ) )
			{
				client. DownloadStringAsync(new Uri(Config. Instance. GetApi(string. Format("{0}&post={1}", NextAppSingleton.Instance.url_post_delete, postID)),
																UriKind. Absolute));
				//显示进度条
				ProgressIndicatorIsVisible = true;
			}
		}
		private bool DisplayResult_DeletePost(ApiError error)
		{
			switch ( error. errorCode )
			{
				case 1:
					MessageBox. Show("文章删除成功");
					return true;
				case 0:
					MessageBox. Show("对不起, 用户未登录, 无法删除");
					return false;
				case -1:
					MessageBox. Show("对不起, 无法删除, 其他错误");
					return false;
				case -2:
					MessageBox. Show("对不起, 您没有删除文章的权限");
					return false;
			}
			return false;
		}

		#endregion

		#region 进度条控制
		void RelativePosts_Loaded(object sender, RoutedEventArgs e)
		{
			SystemTray. ProgressIndicator = new ProgressIndicator( );
			SystemTray. ProgressIndicator. Text = "加载中";
			Binding bindingData = new Binding("ProgressIndicatorIsVisible");
			bindingData. Source = this;
			BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsVisibleProperty, bindingData);
			BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsIndeterminateProperty, bindingData);
		}
		public static readonly DependencyProperty ProgressIndicatorIsVisibleProperty =
			DependencyProperty. Register("ProgressIndicatorIsVisible",
			typeof(bool),
			typeof(RelativePosts),
			new PropertyMetadata(false));
		public bool ProgressIndicatorIsVisible
		{
			get { return ( bool )GetValue(ProgressIndicatorIsVisibleProperty); }
			set { SetValue(ProgressIndicatorIsVisibleProperty, value); }
		}
		#endregion
	}
}
